<?php

class YiiML extends CViewRenderer {
	
	/**
	 * Parses the source view file and saves the results as another file.
	 * @param string the source view file path
	 * @param string the resulting view file path
	 */
	function generateViewFile($sourceFile,$viewFile, $passthru=false) {
	  $data = file_get_contents($sourceFile);
	  if ($passthru) {
	    file_put_contents($viewFile, $data);
	  } else {
	    require_once(getenv("DOCUMENT_ROOT") . "/peml/peml.php");
	    $peml = new pemlCore;
	    $data = $peml->parse($data);
	    file_put_contents($viewFile, $data);
	  }
  }
	
	// Interception for .yiiml file formats.
	// NOTE: Needs an overload of CController->resolveViewFile, to not check file existence.
	public function renderFile($context,$sourceFile,$data,$return)
	{
	  $yiimlSource = substr($sourceFile, 0, strrpos($sourceFile, '.')) . ".yiiml";
	  
		if(is_file($yiimlSource) && ($file=realpath($yiimlSource))!==false) {
		  $passthru = false;
		  $sourceFile = $yiimlSource;
		} elseif(!is_file($sourceFile) || ($file=realpath($sourceFile))===false) {
		  throw new CException(Yii::t('yii','View file "{file}" does not exist.',array('{file}'=>$sourceFile)));
		} else {
		  $passthru = true;
		}
		
		$viewFile=$this->getViewFile($sourceFile);
		if(true || @filemtime($sourceFile)>@filemtime($viewFile))
		{
			$this->generateViewFile($sourceFile,$viewFile, $passthru);
			@chmod($viewFile,$this->filePermission);
		}
		return $context->renderInternal($viewFile,$data,$return);
	}
	
}

?>